package ar.uade.edu.fain.ad.client.delegate.rmi.util;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;

import ar.uade.edu.fain.ad.client.exception.UnavailableServerException;

public class ServiceLocator<T extends Remote> {

	private String serverName = "localhost";
	private Integer serverPort = null;
	private String serviceName;

	public ServiceLocator(String serverName, Integer serverPort,
			String serviceName) {
		super();
		this.serverName = serverName;
		this.serverPort = serverPort;
		this.serviceName = serviceName;
	}

	public ServiceLocator(String serviceName) {
		super();
		this.serviceName = serviceName;
	}

	public ServiceLocator(String serverName, String serviceName) {
		super();
		this.serverName = serverName;
		this.serviceName = serviceName;
	}

	public String getServerName() {
		return serverName;
	}

	public void setServerName(String serverName) {
		this.serverName = serverName;
	}

	public Integer getServerPort() {
		return serverPort;
	}

	public void setServerPort(Integer serverPort) {
		this.serverPort = serverPort;
	}

	public String getServiceName() {
		return serviceName;
	}

	public void setServiceName(String serviceName) {
		this.serviceName = serviceName;
	}

	public String getServiceURL() {
		return "//" + getServerName() + 
				(getServerPort() == null ? 
						"" : (":" + getServerPort().toString())) 
				+ "/" + getServiceName();
	}
	
	@SuppressWarnings("unchecked")
	public T getRemoteService() throws UnavailableServerException {
		try {
			final Remote reference = Naming.lookup(getServiceURL());
			return (T) reference;
		} catch (MalformedURLException e) {
			throw new UnavailableServerException(
					"Mal configurado local?", e);
		} catch (RemoteException e) {
			throw new UnavailableServerException(
					"No disponible: " + e.getMessage(), e);
		} catch (NotBoundException e) {
			throw new UnavailableServerException(
					"Mal configurado remoto?", e);
		}
	}
	
}
